package paytreasure.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;

public class DateConverter implements Converter<String, Date>{
	private static final String DATE      = "yyyy-MM-dd";  
    private static final String DATETIME  = "yyyy-MM-dd HH:mm:ss";  
    private static final String TIMESTAMP = "yyyy-MM-dd HH:mm:ss.SSS";
	/**
	 * 自定义类型转换器
	 */
	public Date convert(String source) {
		if (source == null || "".equals(source)) 
			return null; 
		
		try {
			if (source instanceof String) { 
				String dateValue = source.trim();
				int length = dateValue.length();
				DateFormat formatter = null; 
				if ( length <= 10 ) {
					formatter = new SimpleDateFormat(DATE);
					return formatter.parse(source);
				}
				if ( length <= 19 ) {
					formatter = new SimpleDateFormat(DATETIME);
					return formatter.parse(source);
				}
				if ( length <= 23 ) {
					formatter = new SimpleDateFormat(TIMESTAMP);
					return formatter.parse(source);
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	

}
